<?php
	$loginForm = new Default_Form_Login();
	$auth = Zend_Auth::getInstance()->setStorage(new Zend_Auth_Storage_Session('user'));
	
	$registerForm = new Default_Form_RegisterUser();
	
?>
<div id="menu">
	<ul class="item">
		<li><a href="<?php echo $this->baseUrl(''); ?>">Trang chủ</a></li>
		<li><a href="<?php echo $this->baseUrl('/gioithieu'); ?>">Giới thiệu</a>
		</li>
		<li><a href="<?php echo $this->baseUrl('/tintuc'); ?>">Tin tức</a></li>
		<li><a href="<?php echo $this->baseUrl('/lienhe'); ?>">Liên hệ</a></li>
	</ul>
	<div class="user_action" id="useractionpanel">
		<?php 
			if($auth->hasIdentity()) {
				$infoUser = $auth->getIdentity();
				
				//Cập nhật ngày đăng nhập
				$model = new Default_Model_UsersMapper();
				$model->change($infoUser->id, array('dang_nhap_cuoi' => date('Y-m-d H:i:s')));
				
				echo '<span>Xin chào, <a href="' . $this->baseUrl("/member/profile") . '">' . $infoUser->username . '!</a></span>';
				echo '<span class="logout"><a name="Đăng xuất" href="' . $this->baseUrl("/member/signout") . '">Đăng xuất</a> </span>';
			} else {
		?>
			<span class="register"><a href="#registerModal" data-toggle="modal">Đăng ký</a> </span>
			<span class="login"><a onclick="loginbtnClick()" data-toggle="modal">Đăng nhập</a> </span>
		<?php } ?>
	</div>
	<!-- REGISTER MODAL -->
	<div id="registerModal" class="modal hide fade" data-backdrop="static" tabindex="-1"
		role="dialog" aria-labelledby="registerModalLabel" aria-hidden="true">
		<div class="modal-header">
			<button type="button" class="close" data-dismiss="modal"
				aria-hidden="true">×</button>
			<h3 id="registerModalLabel">Đăng ký tài khoản</h3>
		</div>
		<div class="modal-body" style="max-height: 405px">
			<div id="registeralert" class="alert"></div>
			<form class="form-horizontal">
				<div class="control-group">
					<label class="control-label" for="username">Tên đăng nhập</label>
					<div class="controls">
					<?php echo $registerForm->username;?>
					<p class="hint">Chiều dài 6-12 ký tự, chỉ cho dấu "." và dấu "_".</p>
					</div>
				</div>
				<div class="control-group">
					<label class="control-label" for="password">Mật khẩu</label>
					<div class="controls">
					<?php echo $registerForm->password;?>
					<p class="hint">Chiều dài 6-12 ký tự, được viết hoa và không có ký tự đặc biệt.</p>
					</div>
				</div>
				<div class="control-group">
					<label class="control-label" for="cfrmpassword">Xác nhận lại mật khẩu</label>
					<div class="controls">
					<?php echo $registerForm->cfrmpassword;?>
					</div>
				</div>
				<div class="control-group">
					<label class="control-label" for="email">Email</label>
					<div class="controls">
					<?php echo $registerForm->email;?>
					</div>
				</div>
				<div class="control-group">
					<label class="control-label" for="ho_ten">Họ tên</label>
					<div class="controls">
					<?php echo $registerForm->ho_ten;?>
					</div>
				</div>
				<div class="control-group">
					<label class="control-label" for="ho_ten">Điện thoại</label>
					<div class="controls">
						<?php echo $registerForm->dien_thoai;?>
						<p class="hint">Nhập theo định dạng: (xxx)xxx-xxxx <br />nếu 10 số hay (xxxx)xxx-xxxx nếu 11 số.<br/> Ví dụ: (098)999-9999 hay (0167)999-9999</p>
						<div style="display: table; width: 100%">
							<label class="checkbox">
								<input id="chkAc" type="checkbox" name="chkAc"> &nbsp; Đồng ý với các <a target="_self" href="<?php echo $this->baseUrl('/quydinh'); ?>">quy định</a> của kenhnhatro.com
							</label>
						</div>
					</div>
				</div>
			</form>
		</div>
		<div class="modal-footer">
			<button class="btn" data-dismiss="modal" aria-hidden="true">Đóng</button>
			<button id="btnRegister" class="btn btn-primary">Đồng ý</button>
		</div>
	</div>
	<!-- LOGIN MODAL -->
	<div id="loginModal" class="modal hide fade" data-backdrop="static" tabindex="-1"
		role="dialog" aria-labelledby="loginModalLabel" aria-hidden="true">
		<div class="modal-header">
			<button type="button" class="close" data-dismiss="modal"
				aria-hidden="true">×</button>
			<h3 id="loginModalLabel">Đăng nhập</h3>
		</div>
		<div class="modal-body">
			<div id="loginalert" class="alert"></div>
			<form class="form-horizontal">
				<div class="control-group">
					<label class="control-label" for="login_username">Tên đăng nhập</label>
					<div class="controls">
					<?php echo $loginForm->login_username;?>
					</div>
				</div>
				<div class="control-group">
					<label class="control-label" for="login_password">Mật khẩu</label>
					<div class="controls">
					<?php echo $loginForm->login_password;?>
					</div>
				</div>
				<div class="control-group">
					<div class="controls">
						<div style="display: table; width: 100%;">
							<label class="checkbox">
								<?php echo $loginForm->login_remember;?> &nbsp; Lưu giữ cho lần đăng nhập sau 
							</label>
						</div>
						<div style="display: table;">
							<a href="#" onclick="forgotClick()">Quên mật khẩu</a>
						</div>
					</div>
				</div>
			</form>
		</div>
		<div class="modal-footer">
			<button class="btn" data-dismiss="modal" aria-hidden="true">Đóng</button>
			<button id="loginbtn" class="btn btn-primary">Đăng nhập</button>
		</div>
	</div>
	<!-- FORGOTPASSWORD MODAL -->
	<div id="forgotModal" class="modal hide fade" data-backdrop="static" tabindex="-1"
		role="dialog" aria-labelledby="forgotModalLabel" aria-hidden="true">
		<div class="modal-header">
			<button type="button" class="close" data-dismiss="modal"
				aria-hidden="true">×</button>
			<h3 id="forgotModalLabel">Quên mật khẩu</h3>
		</div>
		<div class="modal-body">
			<div id="forgotalert" class="alert"></div>
			<form class="form-horizontal">
				<p class="notice">Nhập địa chỉ email đã đăng ký, hệ thống sẽ gửi thông tin hướng dẫn bạn khôi phục lại mật khẩu.</p>
				<div class="control-group">
					<label class="control-label" for="email">Email đăng ký</label>
					<div class="controls">
					<?php
						echo $registerForm->email;
					?>
					</div>
				</div>
			</form>
		</div>
		<div class="modal-footer">
			<button onclick="loginbtnClick()" class="btn" data-dismiss="modal" aria-hidden="true">Quay lại</button>
			<button id="forgotbtn" class="btn btn-primary">Gửi</button>
		</div>
	</div>
</div>
<script type="text/javascript" src="<?php echo $this->baseUrl(PUBLIC_PATH . '/js/jqueryForm.js'); ?>"></script>
<script type="text/javascript">
	//************************************************************
	//********************** Process Common **********************
	//************************************************************

	function doValidation(modal, url, action) {
		var data = {};
	    var isValid = true;
	    
		$('#' + modal).find('.alert').hide();
	    $('#' + modal).find("input").each(function() {
	    	$(this).parent().find('.errors').remove();
	        data[$(this).attr('name')] = $(this).val();
	    });
	   	
	    if(action){
			data['action_type'] = 'validate';
		}
		
	    $.ajax({
	        type: 'POST',
	        url: url,
	        async: false,
	        cache: true,
	        data: data,
	        dataType: 'json',
	        success: function(jsonObj) {
	        	$.each(jsonObj, function(key, value) {
	        		isValid = false;
	        		$('#' + modal).find("#" + key).parent().append(getErrorHtml(value, key));        		
		        });
	        }
	    });
	    
	    return isValid;
	}

	//************************************************************
	//********************** Process Login ***********************
	//************************************************************
	
	// Catch keydown event of the enter key
	$('#loginModal').keydown(function (e){
		if(e.keyCode == 13){
			loginProcess(e);
		}
	});
	
	// Catch click event of the login button
	$('#loginbtn').click(function(e) {
		loginProcess(e);
	});

	function loginProcess(event) {
		$('#loginbtn').attr("disabled", "disabled");
		var isValid = doValidation('loginModal', '/member/signinvalidate', null);
		var postData = $("#loginModal form").serializeObject();
		postData.format = "json";
		
		if(isValid){
			$.ajax({
	            type: 'POST',
	            url: '/member/signin',
	            async: true,
	            cache: true,
	            data: postData,
	            dataType: postData.format,
	            success: function(data){
	            	if(data.login) {
	            		setTimeout(function() {
							$('#loginModal').modal('hide'); 
						}, 100);
						
				        $('#useractionpanel').html("<span>Xin chào, <a href='/member/profile'>" + data.user + "!</a></span>");
				        $('#useractionpanel').append("<span class='logout'><a name='Đăng xuất' href='/member/signout'>Đăng xuất</a></span>");
				        window.location.reload();	

		            } else {
	            		if(data.message) {
	                		$('#loginalert').html(data.message);
	                		$('#loginalert').show();
	                    }

	            		$("#loginbtn").removeAttr("disabled");
	                }
	            }
	        });

		} else {
			$("#loginbtn").removeAttr("disabled");
		}
	}

	// Show login modal
	function loginbtnClick() {
		$('#loginModal').modal('show');
	}

	// After show the modal event processing
	$('#loginModal').on('shown', function() {
		$(this).find('.alert').hide();
		$(this).find("input").each(function() {
			var inputid = $(this).attr('id');
			$("#" + inputid).parent().find('.errors').remove();
			$("#" + inputid).val("");
	    });

		$('#loginModal #login_remember').attr('checked', false);
		$('#loginModal input:text:first').focus();
		$('#loginModal input:text:first').select();
		$("#loginbtn").removeAttr("disabled");
	});
	
	//************************************************************
	//********************* Process Register *********************
	//************************************************************
	
	//Catch keydown event of the enter key
	$('#registerModal').keydown(function(e) {
		if(e.keyCode == 13) {
			registerProcess(e);
		}
	});
	
	//Catch click event of the register button
	$('#btnRegister').click(function(e) {
		registerProcess(e);
	});

	function registerProcess(event) {
		$('#btnRegister').attr("disabled", "disabled");
		var isValid = doValidation('registerModal', '/member/register', 'validate');

		if(isValid) {
			if($('#chkAc').is(':checked')) {
				var postData = $("#registerModal form").serializeObject();
				postData['action_type'] = 'register';
				postData.format = "json";
				
				$.ajax({
		            type: 'POST',
		            url: '/member/register',
		            async: true,
		            cache: true,
		            data: postData,
		            dataType: postData.format,
		            success: function(data) {
		            	if(data.register) {
		            		setTimeout(function() {
								$('#registerModal').modal('hide');
							}, 5000);

			            } else {
			            	$("#btnRegister").removeAttr("disabled");
			            }

		            	console.log('Testing console: ' + data.message);
		            	$('#registeralert').html(data.message);
	                	$('#registeralert').show();
		            }
		        });

			} else {
				$('#registeralert').html("Bạn chưa đồng với các quy đinh của kenhnhatro.net.");
	    		$('#registeralert').show();
	    		$('#btnRegister').removeAttr("disabled");
			}

		} else {
			$('#btnRegister').removeAttr("disabled");
		}
	}

	// After show the modal event processing
	$('#registerModal').on('shown', function() {
		$(this).find('.alert').hide();
		$(this).find("input").each(function() {
			var inputid = $(this).attr('id');
			$("#" + inputid).parent().find('.errors').remove();
			$("#" + inputid).val("");
	    });

		$('#registerModal #chkAc').attr('checked', false);
		$('#registerModal input:text:first').focus();
		$('#registerModal input:text:first').select();
		$('#btnRegister').removeAttr("disabled");
	});
	
	//************************************************************
	//**************** Process Forgot Password *******************
	//************************************************************
	
	// Show modal
	function forgotClick() {
		$('#loginModal').modal('hide');
		$('#forgotModal').modal('show');
		$('#forgotalert').hide();
	}
	
	// Catch keydown event of the enter key
	$('#forgotModal').keydown(function(e) {
		if(e.keyCode == 13) {
			forgotProcess(e);
		}
	});
	
	// Catch click event of the register button
	$('#forgotbtn').click(function(e) {
		forgotProcess(e);
	});
	
	function forgotProcess(event) {
		$("#forgotbtn").attr("disabled", "disabled");
		var isValid = doValidation('forgotModal', '/member/forgotpass', 'validate');
		
		if(isValid) {
			var postData = $("#forgotModal form").serializeObject();
			postData['action_type'] = 'forgot';
			postData.format = "json";
			
			$.ajax({
	            type: 'POST',
	            url: '/member/forgotpass',
	            async: true,
	            cache: true,
	            data: postData,
	            dataType: postData.format,
	            success: function(data) {
		            if (data.result) {
	            		setTimeout(function() {
							$('#forgotModal').modal('hide');
						}, 3000);

		            } else {
		            	$("#forgotbtn").removeAttr("disabled");
		            }

            		$('#forgotalert').html(data.message);
            		$('#forgotalert').show();
	            }
	        });

		} else {
			$("#forgotbtn").removeAttr("disabled");
		}
	}

	// After show the modal event processing
	$('#forgotModal').on('shown', function() {
		$('#forgotModal input:text:first').focus();
		$('#forgotModal input:text:first').select();
		$('#forgotModal input:text:first').val('');
		$("#forgotbtn").removeAttr("disabled");
	});
	
</script>
